package com.dckeji.shiplock.webapp.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dckeji.shiplock.framework.constants.SystemConstants;
import com.dckeji.shiplock.framework.pojo.*;
import com.dckeji.shiplock.framework.util.*;
import com.dckeji.shiplock.webapp.dao.IManagerDao;
import com.dckeji.shiplock.webapp.pojo.*;
import com.dckeji.shiplock.webapp.service.IManagerService;
import com.dckeji.shiplock.webapp.util.ReturnMsgUtil;
import org.apache.commons.fileupload.FileItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: TianWei
 * Date: 2017/8/10
 * Time: 17:41
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class ManagerService implements IManagerService {

    @Value("${gaode.url}")
    String url;

    @Value("${wx.ticket}")
    String ticketUrl;

    @Value("${wx.accessToken}")
    String accessTokenUrl;

    @Value("${wx.pushId}")
    String pushId;

    @Value("${wx.pushUrl}")
    String pushUrl;


    @Autowired
    IManagerDao managerDao;

    @Override
    public List<Login> queryManagerLoginHistory() {
        return managerDao.queryManagerLoginHistory();
    }

    @Override
    public SystemMessage querySystemMessage() {


        return managerDao.querySystemMessage();
    }

    @Override
    public Manager managerLogin(Manager manager) {
        manager.setManagerPwd(Md5Util.MD5(manager.getManagerPwd()));
        Manager result = managerDao.queryManagerInfo(manager);
        if (null != result) {
            String managerLoginIp = manager.getManagerLoginIp();
            if (null != managerLoginIp) {
                result.setManagerLoginIp(managerLoginIp);
                HttpClientUtil httpClient = HttpClientUtil.getInstance();
                String requestUrl = url + managerLoginIp;
                String body = httpClient.sendData4Get(requestUrl);
                JSONObject addr = JSON.parseObject(body);
                String province = addr.getString("province");
                String city = addr.getString("city");
                String infocode = addr.getString("infocode");
                String address = "本机";
                if (infocode.equals("10000") && !city.equals("[]")) {
                    managerDao.managerLogin(result, province + city);
                }
                managerDao.managerLogin(result, address);
            }
        }
        return result;
    }

    @Override
    public List<Evaluate> queryNewEvaluates() {


        return managerDao.queryNewEvaluates();
    }

    @Override
    public int examine(Examine examine) {
        int updateRow = 0;
        examine.setExamineTime(DateTimeUtil.getSystemTime());
        switch (examine.getExamineType()) {
            //缴费
            case 1:
                updateRow = managerDao.examinPay(examine);
                break;
            //过闸
            case 2:
                updateRow = managerDao.examinDecla(examine);
                break;
            //延时过号
            case 3:
                updateRow = managerDao.examinTimeoutApply(examine);
                break;
        }
        return updateRow;
    }

    @Override
    public LogicRsult rejectPush(List<Route> routes, String content, Integer optId, String desc, Integer examineType) {
        SingleAccessToken instance = SingleAccessToken.getInstance(accessTokenUrl, ticketUrl);
        WeChatConf weChatConf = instance.getAccessToken();
        String accessToken = weChatConf.getToken();
        String url = pushUrl.replace("ACCESS_TOKEN", accessToken);
        String opt = "";
        //1 缴费退费 2 过闸申报  3 延时过号
        switch (examineType) {
            case 1:
                opt = "缴(退)费审核";
                break;
            case 2:
                opt = "过闸申报";
                break;
            case 3:
                if (examineType == 4) {
                    opt = "过号申请";
                } else {
                    opt = "延时申请";
                }
                break;
        }
        int successCount = 0;
        String errorMsg = "";
        String code = "500";
        for (Route route : routes) {
            String json = "";
            if (optId == 1) {
                json = WeChatUtil.reject(route.getOpenId(), pushId, content, opt, desc);
            } else {
                json = WeChatUtil.success(route.getOpenId(), pushId, content, opt, desc);
            }

            HttpClientUtil http = HttpClientUtil.getInstance();
            String respone = http.sendHttpPost(url, json);
            System.out.println("respone" + respone);
            JSONObject jsonObject = JSONObject.parseObject(respone);
            code = jsonObject.getString("errcode");
            if (code.equals(SystemConstants.ResultCode.SUCCESS)) {
                //推送成功
                successCount++;
            } else {
                errorMsg = jsonObject.getString("errmsg");
            }
        }
        if (successCount > 0 && successCount == routes.size()) {
            //所有人都推送成功
            return ReturnMsgUtil.success();
        } else {
            if (code.equals("40003")) {
                return ReturnMsgUtil.busError("应该推送" + routes.size() + "人，实际推送成功" + successCount + "人，错误原因:未知的openid");
            } else {
                return ReturnMsgUtil.busError("应该推送" + routes.size() + "人，实际推送成功" + successCount + "人，错误代码" + code);

            }
        }
    }

    @Override
    public List<Route> queryRouteByShipNo(String shipNo) {


        return managerDao.queryRouteByShipNo(shipNo);
    }

    @Override
    public int upLoadData(List<FileItem> fileItems) {

        for (Iterator<FileItem> iterator = fileItems.iterator(); iterator.hasNext(); ) {
            FileItem item = iterator.next();
            String fileName = item.getName();
            try {
                if (null != fileName) {
                    System.out.println(fileName);
                    InputStream inputStream = item.getInputStream();
                    if (fileName.indexOf("闸次信息") != -1) {
                        String lock = new LockInfo().execlMap();
                        List<Object> objects = ExcelUtil.readXls(fileName, inputStream, ExcelUtil.getMap(lock), LockInfo.class);
                        if (null != objects && objects.size() > 0) {
                            int row = managerDao.batchUpDateLockInfo(objects);
                            if (row > 0) {
                                return Integer.valueOf(SystemConstants.ResultCode.SUCCESS);
                            }
                        }
                    } else if (fileName.indexOf("过闸信息") != -1) {
                        String map = new UnLockInfo().execlMap();
                        List<Object> objects = ExcelUtil.readXls(fileName, inputStream, ExcelUtil.getMap(map), UnLockInfo.class);
                        int row = managerDao.batchUpDateUnLockInfo(objects);
                        if (row > 0) {
                            return Integer.valueOf(SystemConstants.ResultCode.SUCCESS);
                        }

                    } else if (fileName.indexOf("船舶缴费信息") != -1) {
                        String map = new ShipPayInfo().execlMap();
                        List<Object> objects = ExcelUtil.readXls(fileName, inputStream, ExcelUtil.getMap(map), ShipPayInfo.class);
                        int row = managerDao.batchUpDateUnLockInfo(objects);
                        if (row > 0) {
                            return Integer.valueOf(SystemConstants.ResultCode.SUCCESS);
                        }
                    } else if (fileName.indexOf("船舶复核信息") != -1) {
                        String map = new ReViewInfo().execlMap();
                        List<Object> objects = ExcelUtil.readXls(fileName, inputStream, ExcelUtil.getMap(map), ReViewInfo.class);
                        int row = managerDao.batchUpDateReViewInfo(objects);
                        if (row > 0) {
                            return Integer.valueOf(SystemConstants.ResultCode.SUCCESS);
                        }

                    } else if (fileName.indexOf("船舶登记信息") != -1) {
                        String map = new RegisterInfo().execlMap();
                        List<Object> objects = ExcelUtil.readXls(fileName, inputStream, ExcelUtil.getMap(map), RegisterInfo.class);


                    }

                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return Integer.valueOf(SystemConstants.ResultCode.FIAL);
    }


}
